import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { isReLogin } from './utils/request'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/register', '/forgot'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      // 判断当前用户是否已经有用户信息
      if (!store.getters.role) {
        isReLogin.show = true
        store
          .dispatch('user/GetInfo')
          .then((resp) => {
            isReLogin.show = false
            // 初始化菜单
            store.dispatch('menus/InitMenu').then((resp) => {
              router.addRoutes(resp)
              next({ ...to, replace: true })
            })
          })
          .catch((error) => {
            store.dispatch('user/ResetRouter').then(() => {
              Message.error(error)
              next({ path: '/' })
            })
          })
      } else {
        next()
      }
    }
  } else {
    // 没有登录
    if (whiteList.indexOf(to.path) !== -1) {
      // 白名单，直接放心
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
